<?php namespace Common\Model;
use Hdphp\Model\Model;
//商品操作模型
class Goods extends Model{
	protected $table = "goods";
	protected $validate = array(
		array('gname','required','商品名称不能为空',3,3),
		array('gnum','required','总共参与期数不能为空',3,3),
		array('price','required','商品价格不能为空',3,3),
//		array('upload','required','商品图片必须上传',3,3),
	);
	protected $auto = array(
		array('start_time','time','function',3,1),
	);
	
	
	
	//添加
	public function addData(){
		//如果这时候上传了多张照片，这时候打印post出来的name为img的路径只有一个。这时候要在隐藏域的name名字后面加[]。
		//例如：name="img" ---->>>> name="img[]"   之后再次打印看效果
		/*Array
			(
			    [0] => Upload/Content/16/05/83971464250609.jpg
			    [1] => Upload/Content/16/05/41121464250608.jpg
			    [2] => Upload/Content/16/05/19351464250608.jpg
			)*/
		//sp(Q('post.img'));      
		//die;


		//一、验证***
		//goods 验证失败返回假
		if(!$this->create()) return false;
		//表goods_data 验证失败  返回假
		$goodsDetailsModel = new \Common\Model\GoodsDetails;
		if(!$goodsDetailsModel->create()){
			$this->error = $goodsDetailsModel->getError();
			return false;
		}
		//二、添加
		
		//把post过来的图片数组，用逗号隔开组成字符串。再添加到 字段里面
		
		//post 过来的 需要给一个空数组默认值
		$img = Q('post.img',array());
		$img = implode(',', $img);
		
//		sp($img);
//		die;
		
		//添加列表页商品图片
		$pic = Q('post.pic',array());
		//sp($pic);exit;
		$this->data['pic'] = $pic;
		
		//添加goods商品表，add方法会返回自增id
		$gid = $this->add();
		//2.添加
		$data = array(
			'img'=>$img,
			'details'=>Q('post.details'),
			'goods_gid'=>$gid
		);
		$goodsDetailsModel->add($data);
	
		return true;
	}
	
	//删除商品
	public function realDel($gid){
		//1.删除goods表
		$this->where("gid={$gid}")->delete();
		//2.删除goods_details表
		$goodsDetailsModel = new \Common\Model\GoodsDetails;
		$goodsDetailsModel->where("goods_gid={$gid}")->delete();
		//3.删除goods_periods表
		$goodsPeriodsModel = new \Common\Model\Periods;
		$goodsPeriodsModel->where("goods_gid={$gid}")->delete();
	}
	
	//编辑商品
	public function editData(){
		//1.验证
		//验证goods表
		if(!$this->create()) return false;
		//验证goods_details表
		$goodsDetailsModel = new \Common\Model\GoodsDetails;
		if(!$goodsDetailsModel->create()){
			$this->error = $goodsDetailsModel->getError();
			return false;
		}
		//2.修改
		//修改goods
		$this->save();
		$gid = Q('get.gid',0,'intval');
		
		
		//修改goods_details
		
		$pic = Q('post.img',array());
		$pic = implode(',', $pic);
		
		$data = array(
			'img'=>$pic,
			'details'=>Q('post.details'),
			'goods_gid'=>$gid
		);
		
		$goodsDetailsModel->where("goods_gid={$gid}")->save($data);
			
		return true;
	}
	
}








 ?>